<template>
  <view class="my-order-page">
    <!-- 顶部 Tab 选项 -->
    <scroll-view class="order-tabs" scroll-x>
      <view class="tabs-container">
        <view class="tab-item" v-for="(tab, index) in tabs" :key="index" 
              :class="{ active: activeTab === index }" @click="switchTab(index)">
          {{ tab.name }}
        </view>
      </view>
    </scroll-view>

    <!-- 订单列表 -->
    <view class="order-list">
      <view class="order-item" v-for="(order, index) in filteredOrders" :key="index" 
            @click="goToOrderDetail(order)">
        <view class="order-header">
          <text class="order-no">订单号: {{ order.orderNo }}</text>
          <text class="order-status" :class="getStatusClass(order.state)">
            {{ getStatusText(order.state) }}
          </text>
        </view>

        <view class="order-content">
          <view class="order-details">
            <view class="detail-item">
              <text class="label">预约球桌:</text>
              <text class="value">{{ order.productName }}</text>
            </view>
            <view class="detail-item">
              <text class="label">预约日期:</text>
              <text class="value">{{ order.date }}</text>
            </view>
            <view class="detail-item">
              <text class="label">预约时间:</text>
              <text class="value">{{ order.timeSlot }}</text>
            </view>
            <view class="detail-item">
              <text class="label">时长:</text>
              <text class="value">{{ order.duration }}小时</text>
            </view>
          </view>

          <view class="order-price">
            <text class="total-label">总计:</text>
            <text class="total-price">¥ {{ order.orderPayPrice }}</text>
          </view>
        </view>

        <view class="order-footer" v-if="order.state === 1 && userInfo.isAdmin">
          <button class="cancel-btn" @click.stop="btncancelOrder(order)">取消订单</button>
          <button class="pay-btn" @click.stop="payOrder(order)">立即支付</button>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="filteredOrders.length === 0 && !loading">
        <text class="empty-text">暂无订单</text>
      </view>

      <!-- 加载更多提示 -->
      <view class="loading-more" v-if="loading">
        <text class="loading-text">加载中...</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import {
  ref,
  computed
} from 'vue';
import {
  onShow,
  onReachBottom
} from '@dcloudio/uni-app';
import {
  getOrderList,
  cancelOrder
} from '@/services/order.js';
import {
  formatDateTimeRange
} from '@/utils/date.js';

const userInfo = uni.getStorageSync('userConfig');

// 订单状态枚举
const ORDER_STATUS = {
  ALL: 0,           // 全部订单
  UNPAID: 1,        // 待支付
  CANCELED: 5,      // 已取消
  TO_REDEMPTION: 10, // 待核销
  REFUND: 15,       // 已退款
  REDEMPTION: 20,   // 已核销
  EXPIRED: 25,      // 已过期
};

// Tab选项
const tabs = ref([
  { name: "全部订单" },
  { name: "待支付" },
  { name: "待核销" },
  { name: "已核销" },
  { name: "已退款" },
  { name: "已取消" },
  { name: "已过期" }
]);

// 当前激活的Tab
const activeTab = ref(0);

// 订单数据
const orders = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);
const hasMore = ref(true);

// 根据激活的Tab过滤订单
const filteredOrders = computed(() => {
  return orders.value;
});

// 切换Tab
const switchTab = (index) => {
  if (activeTab.value !== index) {
    activeTab.value = index;
    resetAndReload();
  }
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    [ORDER_STATUS.UNPAID]: "待支付",
    [ORDER_STATUS.CANCELED]: "已取消",
    [ORDER_STATUS.TO_REDEMPTION]: "待核销",
    [ORDER_STATUS.REFUND]: "已退款",
    [ORDER_STATUS.REDEMPTION]: "已核销",
    [ORDER_STATUS.EXPIRED]: "已过期",
  };
  return statusMap[status] || "未知状态";
};

// 获取状态样式类
const getStatusClass = (status) => {
  const statusClassMap = {
    [ORDER_STATUS.UNPAID]: "status-pending",
    [ORDER_STATUS.CANCELED]: "status-cancelled",
    [ORDER_STATUS.TO_REDEMPTION]: "status-paid",
    [ORDER_STATUS.REFUND]: "status-refunded",
    [ORDER_STATUS.REDEMPTION]: "status-completed",
    [ORDER_STATUS.EXPIRED]: "status-expired",
  };
  return statusClassMap[status] || "";
};

// 跳转到订单详情
const goToOrderDetail = (order) => {
  uni.navigateTo({
    url: `/pages/mine/orderDetails?orderNo=${order.orderNo}`
  });
};

// 取消订单
const btncancelOrder = (order) => {
  uni.showModal({
    title: "确认取消",
    content: "确定要取消该订单吗?",
    success: async function(res) {
      if (res.confirm) {
        const data = await cancelOrder(order.orderNo);
        if (data.code === 200) {
          uni.showToast({
            title: "取消成功",
            icon: "success"
          });
          resetAndReload();
        } else {
          uni.showToast({
            title: "取消失败",
            icon: "none"
          });
        }
      }
    }
  });
};

// 支付订单
const payOrder = (order) => {
  uni.navigateTo({
    url: `/pages/list/payDetail?orderNo=${order.orderNo}`
  });
};

// 重置并重新加载数据
const resetAndReload = () => {
  orders.value = [];
  currentPage.value = 1;
  total.value = 0;
  hasMore.value = true;
  loadOrders();
};

// 加载订单数据
const loadOrders = async () => {
  if (loading.value || !hasMore.value) return;
  loading.value = true;
  try {
    // 构造查询参数
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };

    // 添加状态过滤条件 - 使用索引值代替status属性
    if (activeTab.value !== 0) {
      // 根据tab索引映射到对应的状态值
      const statusMap = [
        null, // 全部订单
        ORDER_STATUS.UNPAID, // 待支付
        ORDER_STATUS.TO_REDEMPTION, // 待核销
        ORDER_STATUS.REDEMPTION, // 已核销
        ORDER_STATUS.REFUND, // 已退款
        ORDER_STATUS.CANCELED, // 已取消
        ORDER_STATUS.EXPIRED, // 已过期
      ];
      const status = statusMap[activeTab.value];
      if (status !== null) {
        params.state = status;
      }
    }

    const res = await getOrderList(params);
    if (res.data) {
      const newOrders = res.data.list || [];

      // 处理每个订单的日期和时间信息
      newOrders.forEach(order => {
        if (order.dateTimeRangeList) {
          const {
            formattedDate,
            formattedTimeSlot
          } = formatDateTimeRange(order.dateTimeRangeList);
          order.date = formattedDate;
          order.timeSlot = formattedTimeSlot;
          order.duration = order.dateTimeRangeList.length;
        }
      });

      // 将total转换为数字类型
      total.value = parseInt(res.data.total) || 0;

      // 更新订单数据
      orders.value = [...orders.value, ...newOrders];

      // 判断是否还有更多数据
      hasMore.value = orders.value.length < total.value;
    }
  } catch (error) {
    console.error('获取订单失败:', error);
    uni.showToast({
      title: "获取订单失败",
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 页面触底加载更多
const onReachBottomHandler = () => {
  if (hasMore.value && !loading.value) {
    currentPage.value++;
    loadOrders();
  }
};

// 页面加载
onShow(() => {
  loadOrders();
});

onReachBottom(() => {
  onReachBottomHandler();
});
</script>

<style lang="scss">
.my-order-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .order-tabs {
    background-color: #fff;
    
    .tabs-container {
      white-space: nowrap;
      
      .tab-item {
        display: inline-block;
        padding: 15px 12px;
        font-size: 14px;
        color: #666;
        position: relative;
        min-width: 60px;
        text-align: center;
        
        &.active {
          color: #1e5dff;
          font-weight: bold;
          
          &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 30px;
            height: 3px;
            background-color: #165dff;
            border-radius: 3px;
          }
        }
      }
    }
  }
  
  .order-list {
    padding: 10px;
    
    .order-item {
      background-color: #fff;
      border-radius: 8px;
      margin-bottom: 10px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      overflow: hidden;
      
      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 15px;
        border-bottom: 1px solid #f0f0f0;
        
        .order-no {
          font-size: 14px;
          color: #999;
        }
        
        .order-status {
          font-size: 13px;
          padding: 3px 8px;
          border-radius: 3px;
          
          &.status-pending {
            color: #ff9900;
            background-color: rgba(255, 153, 0, 0.1);
          }
          
          &.status-paid {
            color: #1e5dff;
            background-color: rgba(22, 93, 255, 0.1);
          }
          
          &.status-completed {
            color: #0ecc66;
            background-color: rgba(0, 204, 102, 0.1);
          }
          
          &.status-refunded {
            color: #999999;
            background-color: rgba(153, 153, 153, 0.1);
          }
          
          &.status-cancelled {
            color: #999999;
            background-color: rgba(153, 153, 153, 0.1);
          }
          
          &.status-partial-refund {
            color: #ff6666;
            background-color: rgba(255, 102, 0, 0.1);
          }
        }
      }
      
      .order-content {
        padding: 15px;
        
        .table-info {
          margin-bottom: 12px;
          
          .table-name {
            font-size: 16px;
            font-weight: bold;
            color: #333;
          }
        }
        
        .order-details {
          .detail-item {
            display: flex;
            margin-bottom: 8px;
            
            .label {
              flex: 1;
              font-size: 13px;
              color: #999;
            }
            
            .value {
              flex: 2;
              font-size: 13px;
              color: #666;
              text-align: right;
            }
          }
        }
        
        .order-price {
          display: flex;
          justify-content: flex-end;
          align-items: center;
          margin-top: 10px;
          padding-top: 10px;
          border-top: 1px dashed #f0f0f0;
          
          .total-label {
            font-size: 14px;
            color: #999;
            margin-right: 5px;
          }
          
          .total-price {
            font-size: 16px;
            font-weight: bold;
            color: #ff6666;
          }
        }
      }
      
      .order-footer {
        display: flex;
        justify-content: flex-end;
        padding: 10px 15px;
        border-top: 1px solid #f0f0f0;
        
        .cancel-btn,
        .pay-btn {
          font-size: 13px;
          padding: 6px 15px;
          border-radius: 4px;
          margin-left: 10px;
        }
        
        .cancel-btn {
          color: #999;
          background-color: #f5f5f5;
          border: 1px solid #e0e0e0;
        }
        
        .pay-btn {
          color: #fff;
          background-color: #165dff;
          border: 1px solid #165dff;
        }
      }
    }
    
    .empty-state {
      text-align: center;
      padding: 50px 0;
      
      .empty-text {
        font-size: 16px;
        color: #999;
      }
    }
    
    .loading-more {
      text-align: center;
      padding: 15px 0;
      
      .loading-text {
        font-size: 14px;
        color: #999;
      }
    }
  }
}
</style>